/* Copyright 2012 Ali H. Caliskan.  All rights reserved.

   This file is part of Sysmkr.

   Sysmkr is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package main

import (
	"fmt"
	"path/filepath"
	"libmkr"
)

var (
	ImgDir = libmkr.ImgDir
)


func SyncImage(root string) {

	libmkr.MkDir(root)

	args := []string{"sync-grp", "infra", root, "--grp-syscfg"}
	libmkr.Run("sysmkr", args...)

	args = []string{"/etc/resolv.conf", filepath.Join(root, "etc")}
	libmkr.Run("cp", args...)

	args = []string{libmkr.GlobalSQLite, filepath.Join(root, "system/pkg")}
	libmkr.Run("cp", args...)

	args = []string{"--bind", "/dev", filepath.Join(root, "dev")}
	libmkr.Run("mount", args...)

	args = []string{root, "/bin/bash", "-c", "syscfg sync-arrange infra"}
	libmkr.Run("chroot", args...)

	kvers := libmkr.GetInfoPkg(libmkr.GlobalSQLite, "linux")[1]
	args = []string{root, "/bin/bash", "-c", "dracut /boot/initramfs-" + kvers + " " + kvers}
	libmkr.Run("chroot", args...)
}


func GrubImage(root string, device string) {

	args := []string{"--force", "--root-directory=" + root, device}
	libmkr.Run("grub-install", args...)

}


func FreeImage(root string) {

	args := []string{"-l", filepath.Join(root, "dev")}
	libmkr.Run("umount", args...)

	libmkr.RmDir(root)
}


func main() {

	flag := libmkr.GetArg(0)
	_dir := libmkr.GetArg(1)
	_dev := libmkr.GetArg(2)

	if _dir != "" {
		ImgDir = _dir
	}

	switch flag {

	case "sync":
		SyncImage(ImgDir)
	case "grub":
		GrubImage(ImgDir, _dev)
	case "free":
		FreeImage(ImgDir)
	case "":
		fmt.Println("warning: missing flag")
	}
}

